<script lang="ts" setup>
import { defineEmits, nextTick, ref, watch } from 'vue';

import { $t } from '@vben/locales';

import { Button, Form, Input, message, Modal, Select } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';

interface DictOption {
  id?: number | string;
  paramKey: string;
  sourceType: 'field' | 'fixed';
  value: string;
}

interface FormFieldOption {
  label: string;
  field: string;
}

interface Props {
  value?: DictOption[] | string;
  formFieldList?: FormFieldOption[];
}

interface Emits {
  (e: 'update:value', value: DictOption[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formData = ref<Partial<DictOption>>({});
const modalVisible = ref(false);

const parseDictOptions = (value: DictOption[] | string = ''): DictOption[] => {
  if (!value) return [];
  if (Array.isArray(value)) return value;
  if (typeof value === 'string') {
    try {
      return JSON.parse(value);
    } catch {
      return [];
    }
  }
  return [];
};

const syncDataToParent = () => {
  const data = gridApi.grid?.getTableData().tableData || [];
  emit('update:value', data);
};

// 表格配置
const createGridOptions = (): VxeGridProps<DictOption> => ({
  columns: [
    { type: 'seq', title: '序号', width: 60 },
    {
      field: 'sourceType',
      title: '参数来源',
      editRender: {
        name: 'select',
        options: [
          { label: '固定值', value: 'fixed' },
          { label: '表单字段', value: 'field' },
        ],
      },
      minWidth: 120,
    },
    {
      field: 'paramKey',
      title: '参数名',
      editRender: { name: 'input' },
      minWidth: 140,
    },
    {
      field: 'value',
      title: '值 / 绑定字段',
      minWidth: 180,
      editRender: {
        name: ({ row }) => (row.sourceType === 'field' ? 'select' : 'input'),
        options: ({ row }) =>
          row.sourceType === 'field'
            ? props.formFieldList?.map((f) => ({
                label: f.label,
                value: f.field,
              }))
            : undefined,
      },
    },
    { slots: { default: 'action' }, title: '操作', width: 80, align: 'center' },
  ],
  data: [],
  editConfig: {
    mode: 'row',
    trigger: 'manual', // 手动触发编辑，不响应点击
    showStatus: true,
  },

  height: 400,
  keepSource: true,
  rowConfig: { keyField: 'id' },
  toolbarConfig: {
    refresh: true,
    search: true,
  },
  pagerConfig: { enabled: false },
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: createGridOptions(),
});

watch(
  () => props.value,
  (newValue) => {
    const data = parseDictOptions(newValue);
    nextTick(() => gridApi.setGridOptions({ data }));
  },
  { immediate: true, deep: true },
);

// 打开新增 Modal
const openModal = () => {
  formData.value = { sourceType: 'fixed', paramKey: '', value: '' };
  modalVisible.value = true;
};

// 提交表单
const handleOk = async () => {
  if (!formData.value.paramKey) {
    message.error('请输入参数名');
    return;
  }

  // 校验 paramKey 是否重复
  const existingData: DictOption[] =
    gridApi.grid?.getTableData().tableData || [];
  const isDuplicate = existingData.some(
    (row) =>
      row.paramKey === formData.value.paramKey && row.id !== formData.value.id,
  );
  if (isDuplicate) {
    message.error('参数名不能重复');
    return;
  }

  const newRow: DictOption = {
    ...formData.value,
    id: Date.now(),
  };

  gridApi.grid?.insertAt(newRow, -1);
  syncDataToParent();
  modalVisible.value = false;
};

// 删除行
const deleteRow = async (row: DictOption) => {
  await gridApi.grid?.remove(row);
  message.success('删除成功');
  syncDataToParent();
};
</script>

<template>
  <div class="dict-options-table">
    <Grid>
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['参数']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              onClick: openModal,
            },
          ]"
        />
      </template>
      <template #action="{ row }">
        <Button type="link" danger @click="deleteRow(row)">删除</Button>
      </template>
    </Grid>

    <Modal v-model:visible="modalVisible" title="新增参数" @ok="handleOk">
      <Form layout="vertical">
        <Form.Item label="参数名" required>
          <Input v-model:value="formData.paramKey" placeholder="请输入参数名" />
        </Form.Item>
        <Form.Item label="参数来源" required>
          <Select v-model:value="formData.sourceType" placeholder="请选择来源">
            <Select.Option value="fixed">固定值</Select.Option>
            <Select.Option value="field">表单字段</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="值 / 绑定字段" required>
          <Input
            v-if="formData.sourceType === 'fixed'"
            v-model:value="formData.value"
            placeholder="请输入参数值"
          />
          <Select
            v-else
            v-model:value="formData.value"
            placeholder="请选择字段"
          >
            <Select.Option
              v-for="f in props.formFieldList"
              :key="f.field"
              :value="f.field"
            >
              {{ f.label }}
            </Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.dict-options-table {
  width: 100%;
}

.dict-options-table :deep(.vxe-toolbar) {
  margin-bottom: 8px;
}
</style>
